package com.etoak.controller;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.redis.service.RedisService;
import com.etoak.vo.CodeVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    RedisService redisService;

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @GetMapping("/getCode")
    public ResultVO<CodeVO> getCode() throws IOException {
        String text = defaultKaptcha.createText();
        // 1+1=>@2 变为数组 ["1+1=?","2"]
        String[] textArray = text.split(StrUtil.AT);

        // 将表达式结果放入 redis
        String uuid = IdUtil.simpleUUID();
        String codeKey = CommonConstant.CODE_KEY_PREFIX + uuid;
        redisService.setex(codeKey,textArray[1],5, TimeUnit.MINUTES);

        // 生成图片，将图片写入字节数组输出流（可以将图片转成 byte 数组）
        BufferedImage bufferedImage = defaultKaptcha.createImage(textArray[0]);
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", outputStream);

        String base64Code = Base64.encode(outputStream.toByteArray());
        String codeUrl = "data:image/png;base64," + base64Code;

        // 将图片的字节数组转成 base64 编码
        CodeVO codeVO = new CodeVO(uuid,codeUrl);

        return ResultVO.success(codeVO);

    }

}
